package com.yhq.basic.jvm.classload.others;

import java.io.FileInputStream;

/**
 * @author hqyin
 * @date 2023/3/1 5:08 下午
 */
public class DestroyClassLoad extends ClassLoader {
    private String classPath;

    public DestroyClassLoad(String classPath) {
        this.classPath = classPath;
    }

    @Override
    public Class<?> loadClass(String name) throws ClassNotFoundException {
        synchronized (getClassLoadingLock(name)) {
            //获取已经加载过的类对象
            Class<?> c = findLoadedClass(name);
            if (c == null) {
                //自定义类路径，自己加载，否则走默认类加载机制,
                if (name.contains("yhq")) {
                    c = findClass(name);
                } else {
                    c = super.loadClass(name);
                }
            }

            return c;
        }

    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        try {
            byte[] data = loadData(name);
            return super.defineClass(name, data, 0, data.length);
        } catch (Exception e) {
            throw new ClassNotFoundException();
        }
    }

    private byte[] loadData(String name) throws Exception {
        String filePath = name.replace('.', '/').concat(".class");
        String fullPath = classPath + "/" + filePath;
        FileInputStream inputStream = new FileInputStream(fullPath);
        int len = inputStream.available();
        byte[] data = new byte[len];
        inputStream.read(data);
        inputStream.close();
        return data;
    }
}
